package com.roam.mapper;

import com.roam.Ant.AntColonyOptimization;
import com.roam.DTO.SceneDetailDTO;
import com.roam.DTO.TourPlanDTO;
import com.roam.VO.DisplaySceneVO;
import com.roam.VO.TourPlanVO;
import com.roam.entity.scene.Scene;
import com.roam.mgdb.MongoUtils;
import jakarta.annotation.Resource;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class SelectPageMapper {
    @Autowired
    private MongoUtils mongoUtils = new MongoUtils();
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    public List<TourPlanVO> getPopularScenes(String city) {
        ValueOperations<String,Object> valueOperations= redisTemplate.opsForValue();
        List<TourPlanVO> popularScenes=new ArrayList<>();
        String key = "PopularScenes-"+city;
        if(redisTemplate.hasKey(key)){

            popularScenes= (List<TourPlanVO>) valueOperations.get(key);
            if(!popularScenes.isEmpty()) {
                return popularScenes;
            }
        }
         popularScenes = mongoUtils.docToTourPlanVOS(mongoUtils.getHeatDescendingData(20, city),50);
        valueOperations.set(key,popularScenes,1, TimeUnit.DAYS);
        return popularScenes;
    }

    public List<List<List<TourPlanVO>>> getTourPlan(TourPlanDTO tourPlanDTO) {
        List<List<List<TourPlanVO>>> tourPlans = new ArrayList<>();

        List<TourPlanVO> userChoosingScenes = new ArrayList<>();
        for (SceneDetailDTO sceneDetailDTO : tourPlanDTO.getUserChoosingScenes()) {
            TourPlanVO userChoosingScene = mongoUtils.getSceneTourPlanVO(sceneDetailDTO.getCity(), sceneDetailDTO.getSceneID());

            userChoosingScenes.add(userChoosingScene);
        }

        AntColonyOptimization antColonyOptimization;
        for (List<List<TourPlanVO>> originalTourPlan : mongoUtils.tourPlan(tourPlanDTO.getCity(), userChoosingScenes, tourPlanDTO.getDays())) {
            List<List<TourPlanVO>> tourPlan = new ArrayList<>();
            for (List<TourPlanVO> tourPlanVOS : originalTourPlan) {
                antColonyOptimization = new AntColonyOptimization(tourPlanVOS);
                antColonyOptimization.runAntColonyOptimization();
                tourPlan.add(antColonyOptimization.getBestPath());
            }
            tourPlans.add(tourPlan);
        }
        return tourPlans;
//        return mongoUtils.tourPlan(tourPlanDTO.getCity(), userChoosingScenes, tourPlanDTO.getDays());
    }
}
